﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class UserControl_TableAndColumn : System.Web.UI.UserControl
{
    public bool SelectAll
    {
        get
        {
            bool SelectAll = true;
            object obj = ViewState["SELECTALL"];
            if (obj != null)
            {
                SelectAll = Convert.ToBoolean(ViewState["SELECTALL"]);
            }
            return SelectAll;

        }
        set
        {
            ViewState["SELECTALL"] = value;
        }

    }
    public string SQLString
    {
        get
        {
            string sqlString = "";
            object obj = ViewState["SQLString"];
            if (obj != null)
            {
                sqlString = ViewState["SQLString"].ToString();
            }
            return sqlString;
        }
        set
        {
            ViewState["SQLString"] = value;
        }

    }
    protected void Page_Load(object sender, EventArgs e)
    {

    }
   
    protected void CheckBoxList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        GetSQLString();
    }

    public void GetSQLString()
    {
        string sql = "select #TOP# {0} from {1}";
        string cols = "";
        foreach (ListItem item in CheckBoxList1.Items)
        {
            if (item.Selected)
            {
                if (item.Value.Contains("(") || item.Value.Contains(")"))
                    cols += "["+item.Value+"]" + ", ";
                else
                cols += item.Value + ", ";
            }
        }

        if (cols.Length > 2)
        {
            SQLString = string.Format(sql, cols.Substring(0, cols.Length - 2), DropDownList1.SelectedValue);
        }
        else { SQLString = ""; }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        foreach (ListItem item in CheckBoxList1.Items)
        {
            item.Selected = SelectAll;
        }
        if (Button1.Text.Equals("全選"))
        {
            Button1.Text = "取消全選";
            SelectAll = false;
        }
        else if (Button1.Text.Equals("取消全選"))
        {
            Button1.Text = "全選";
            SelectAll = true;
        }
        GetSQLString();
    }
}
